package com.ruan.quartz;

import javax.servlet.http.HttpSession;
import java.util.Iterator;  
import java.util.Map;  
import java.util.concurrent.ConcurrentHashMap;  

public class SessionManager {
    // 设置最大不活跃时间
    private static final long MAX_INACTIVE_INTERVAL = 6000; // 30分钟  30 * 60 * 1000
    private static Map<String, HttpSession> sessions = new ConcurrentHashMap<>();  

    public static void addSession(String sessionId, HttpSession session) {  
        sessions.put(sessionId, session);  
    }  

    public static void removeSession(String sessionId) {  
        sessions.remove(sessionId);  
    }  

    public static void cleanUpSessions() {  
        long currentTime = System.currentTimeMillis();  
        Iterator<Map.Entry<String, HttpSession>> iterator = sessions.entrySet().iterator();  
        
        while (iterator.hasNext()) {  
            Map.Entry<String, HttpSession> entry = iterator.next();  
            HttpSession session = entry.getValue();
            // 判断是否超过最大不活跃时间
            if (currentTime - session.getLastAccessedTime() > MAX_INACTIVE_INTERVAL) {
                System.out.println("清理会话");
                iterator.remove();  
                session.invalidate(); // 使会话失效  
            }  
        }  
    }  
}